/**
 * Filename: ProfileActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/2/26 17:58
 */
package com.github.postsanf.yinian.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.pop.PopSetAvatar;
import com.github.postsanf.yinian.bean.YNUser;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.utils.Crop;
import com.github.postsanf.yinian.utils.DateTimePickDialogUtil;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ImageUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.github.postsanf.yinian.utils.StringUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.utils.Log;

import org.json.JSONObject;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.UUID;

public class ProfileActivity extends BaseActivity implements View.OnClickListener, ISkinUpdate {
    private Toolbar mToolbar;
    private YNUser curUser;
    private RelativeLayout rl_profile_avatar;
    private RelativeLayout rl_profile_bg;
    private RelativeLayout rl_profile_name;
    private RelativeLayout rl_profile_sex;
    private RelativeLayout rl_profile_birthday;
    private ImageView iv_user_avatar;
    private ImageView iv_user_bg;
    private TextView tv_user_nickname;
    private TextView tv_user_sex;
    private TextView tv_user_birthday;
    private ImageView iv_sex_man;
    private ImageView iv_sex_woman;
    private AlertDialog alertDialog;
    private String userAvatar_alert;                            // 头像
    private String userBirthday_alert;                            // 生日
    private String userSex_alert;                                // 性别
    private String userName_alert;                                // 昵称
    private ProgressDialog mProgressDialog;                            // 进度条
    private String imagelocal;
    private UploadManager mUpManager;
    private File mTempDir;
    private LinearLayout main_content;
    private boolean isAvatar = true;
    private PopSetAvatar mpopSetAvatar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_profile);
        BaseApplication.getInstance().mActivitys.add(this);
        mUpManager = application.getUploadManager();
        mTempDir = new File(Environment.getExternalStorageDirectory(), "yinian/temp");
        if (!mTempDir.exists()) {
            mTempDir.mkdirs();
        }
        curUser = application.getCurUser();
        initView();
    }

    private void initView() {
        mpopSetAvatar = new PopSetAvatar(ProfileActivity.this, itemsOnClick, itemsOnTouch);
        mToolbar = (Toolbar) findViewById(R.id.profile_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
        main_content = (LinearLayout) findViewById(R.id.main_content);
        rl_profile_avatar = (RelativeLayout) findViewById(R.id.rl_profile_avatar);
        rl_profile_bg = (RelativeLayout) findViewById(R.id.rl_profile_bg);
        rl_profile_name = (RelativeLayout) findViewById(R.id.rl_profile_name);
        rl_profile_sex = (RelativeLayout) findViewById(R.id.rl_profile_sex);
        rl_profile_birthday = (RelativeLayout) findViewById(R.id.rl_profile_birthday);
        iv_user_avatar = (ImageView) findViewById(R.id.iv_user_avatar);
        iv_user_bg = (ImageView) findViewById(R.id.iv_user_bg);
        tv_user_nickname = (TextView) findViewById(R.id.tv_user_nickname);
        tv_user_sex = (TextView) findViewById(R.id.tv_user_sex);
        tv_user_birthday = (TextView) findViewById(R.id.tv_user_birthday);

        rl_profile_avatar.setOnClickListener(this);
        rl_profile_bg.setOnClickListener(this);
        rl_profile_name.setOnClickListener(this);
        rl_profile_sex.setOnClickListener(this);
        rl_profile_birthday.setOnClickListener(this);
        imageLoader.displayImage(curUser.getUbackground(), new ImageViewAware(iv_user_bg, false), ImageOptHelper.getCornerOptions(2));
        imageLoader.displayImage(curUser.getUpic(), new ImageViewAware(iv_user_avatar, false), ImageOptHelper.getAvatarOptions());
        if (StringUtils.isEmpty(curUser.getUnickname())) {
            tv_user_nickname.setText("");
        } else {
            tv_user_nickname.setText(curUser.getUnickname());
        }
        String sexflag = "1";
        if (curUser.getUsex() != null) {
            tv_user_sex.setText(sexflag.equals(curUser.getUsex()) ? "男" : "女");
        }
        if (curUser.getUbirth() != null) {
            tv_user_birthday.setText(curUser.getUbirth());
        }
        // 性别修改
        tv_user_sex.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (curUser.getUsex() == null) {
                    return;
                }
                if ((curUser.getUsex().equals("1") ? "男" : "女").equals(userSex_alert)) {
                    return;
                }
                alertSingleInfo(CommonConstants.YNS_SEX, userSex_alert);
            }
        });
        // 生日修改
        tv_user_birthday.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                userBirthday_alert = tv_user_birthday.getText().toString().trim();
                if (curUser.getUbirth() == null) {
                    return;
                }
                if (curUser.getUbirth().equals(userBirthday_alert)) {
                    return;
                }
                alertSingleInfo(CommonConstants.YNS_BIRTHDAY, userBirthday_alert);
            }
        });
    }

    //	头像
    private View.OnTouchListener itemsOnTouch = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int height = mpopSetAvatar.mMenuView.findViewById(R.id.pop_setuser_advatar_layout).getTop();
            int y = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (y < height) {
                    mpopSetAvatar.dismiss();
                }
            }
            return true;
        }
    };

    // 头像监听
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        public void onClick(View v) {
            mpopSetAvatar.dismiss();
            switch (v.getId()) {
                case R.id.btn_setuser_take_photo:
                    ImageUtils.pickImageFromCamera(ProfileActivity.this);
                    break;
                case R.id.btn_setuser_pick_photo:
                    ImageUtils.pickImageFromAlbum(ProfileActivity.this);
                    break;
                case R.id.btn_setuser_cancel_photo:
                    break;
            }
        }
    };

    // 性别修改
    private void initAlertSex(String sexStr) {
        View sexView = View.inflate(this, R.layout.yn_common_sex, null);
        LinearLayout ll_sex_man = (LinearLayout) sexView.findViewById(R.id.ll_sex_man);
        LinearLayout ll_sex_woman = (LinearLayout) sexView.findViewById(R.id.ll_sex_woman);
        iv_sex_man = (ImageView) sexView.findViewById(R.id.iv_sex_man);
        iv_sex_woman = (ImageView) sexView.findViewById(R.id.iv_sex_woman);
        if (sexStr.equals("男")) {
            alertSexImgToMan(true);
        } else {
            alertSexImgToMan(false);
        }
        alertDialog = new AlertDialog.Builder(this).show();
        alertDialog.setCanceledOnTouchOutside(true);
        alertDialog.setContentView(sexView);
        WindowManager.LayoutParams layout = alertDialog.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 32 * 2);
        alertDialog.getWindow().setAttributes(layout);
        // 男
        ll_sex_man.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertSexImgToMan(true);
                userSex_alert = "男";
                tv_user_sex.setText(userSex_alert);
                alertDialog.dismiss();
            }
        });
        // 女
        ll_sex_woman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertSexImgToMan(false);
                userSex_alert = "女";
                tv_user_sex.setText(userSex_alert);
                alertDialog.dismiss();
            }
        });
    }

    private void alertSexImgToMan(boolean isMan) {
        if (isMan) {
            iv_sex_man.setVisibility(View.VISIBLE);
            iv_sex_woman.setVisibility(View.GONE);
        } else {
            iv_sex_woman.setVisibility(View.VISIBLE);
            iv_sex_man.setVisibility(View.GONE);
        }
    }

    // 处理图像剪切结果
    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == Activity.RESULT_OK) {
            imagelocal = ImageUtils.getImageAbsolutePath19(this, Crop.getOutput(result));
            if (isAvatar) {
                imageLoader.displayImage("file:///" + imagelocal, iv_user_avatar, ImageOptHelper.getAvatarOptions());
                Intent intent = new Intent();
                intent.setAction(ACTIONs.Avatar);
                intent.putExtra("avatarUri", imagelocal);
                sendBroadcast(intent);
                getToken();
            } else {
                imageLoader.displayImage("file:///" + imagelocal, iv_user_bg, ImageOptHelper.getCornerOptions(2));
                getToken();
            }
        } else if (resultCode == Crop.RESULT_ERROR) {
            showToast("处理图片失败");
        }
    }

    // 开始剪切过程
    private void beginCrop(Uri source) {
        String fileName = "Temp_" + String.valueOf(System.currentTimeMillis()) + ".png";
        File cropFile = new File(mTempDir, fileName);
        Uri outputUri = Uri.fromFile(cropFile);
        new Crop(source).output(outputUri).setCropType(false).start(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ImageUtils.REQUEST_CODE_FROM_ALBUM:
                if (resultCode == RESULT_CANCELED) {
                    return;
                }
                Uri imageUri = data.getData();
                beginCrop(imageUri);
                break;
            case ImageUtils.REQUEST_CODE_FROM_CAMERA:
                if (resultCode == RESULT_CANCELED) {
                    ImageUtils.deleteImageUri(this, ImageUtils.imageUriFromCamera);
                } else {
                    Uri imageUriCamera = ImageUtils.imageUriFromCamera;
                    beginCrop(imageUriCamera);
                }
                break;
            case Crop.REQUEST_CROP:
                handleCrop(resultCode, data);
                break;
            //  修改昵称回调
            case CommonConstants.REQ_ALERT_GNAME:
                if (resultCode == RESULT_CANCELED) {
                    return;
                }
                userName_alert = data.getStringExtra(CommonConstants.REQ_DATA);
                if (StringUtils.isEmpty(userName_alert))
                    return;
                tv_user_nickname.setText(userName_alert);
                alertSingleInfo(CommonConstants.YNS_NICKNAME, userName_alert);
                break;
            default:
                break;
        }
    }

    // 单条信息 修改
    private void alertSingleInfo(final String type, final String data) {
        Log.i("xjs", "alertSingleInfo==>");
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_INFO_DATA, data);
        mParam.put(CommonConstants.YNS_INFO_TYPE, type);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynModifySinInfo)).setMethod(HttpMethods.Post).setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resAlertUser = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resAlertUser.getCode())) {
                            switch (type) {
                                case CommonConstants.YNS_PIC:
                                    curUser.setUpic("file:///" + imagelocal);
                                    application.getCurUser().setUpic("file:///" + imagelocal);
                                    break;
                                case CommonConstants.YNS_SEX:
                                    curUser.setUsex(userSex_alert.equals("男") ? "1" : "0");
                                    application.getCurUser().setUsex(ReqUtils.sexIsInt(userSex_alert, false));
                                    break;
                                case CommonConstants.YNS_BIRTHDAY:
                                    curUser.setUbirth(userBirthday_alert);
                                    application.getCurUser().setUbirth(userBirthday_alert);
                                    break;
                                case CommonConstants.YNS_NICKNAME:
                                    curUser.setUnickname(userName_alert);
                                    application.getCurUser().setUnickname(userName_alert);
                                    break;
                            }
                            showToast("修改成功");
                            sendBroadcast(new Intent(ACTIONs.actionAlertMeBg));
                        } else {
                            switch (type) {
                                case CommonConstants.YNS_PIC:
                                    imageLoader.displayImage(curUser.getUpic(), new ImageViewAware(iv_user_avatar, false), ImageOptHelper.getAvatarOptions());
                                    break;
                                case CommonConstants.YNS_SEX:
                                    tv_user_sex.setText(curUser.getUsex().equals("1") ? "男" : "女");
                                    break;
                                case CommonConstants.YNS_BIRTHDAY:
                                    tv_user_birthday.setText(curUser.getUbirth());
                                    break;
                                case CommonConstants.YNS_NICKNAME:
                                    tv_user_nickname.setText(curUser.getUnickname());
                                    break;
                            }
                            showToast("修改失败");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 获取上传Token
    private void getToken() {
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            application.setUpToken(resToken.getData().get(0).getToken());
                            getAvatarAddress();
                        } else {
                            showToast(resToken.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 获取七牛云头像地址
    private void getAvatarAddress() {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        String prefix = imagelocal.substring(imagelocal.lastIndexOf(".") + 1);
        final String imgName = UUID.randomUUID().toString() + "." + prefix;
        mUpManager.put(imagelocal, imgName, application.getUpToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        userAvatar_alert = key;
                        if (isAvatar) {
                            alertSingleInfo(CommonConstants.YNS_PIC, key);
                        } else {
                            doBgPost(key, imgName);
                        }
                        mProgressDialog.dismiss();
                    }
                }, new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            public void progress(String key, double percent) {
                            }
                        }, null));
    }

    private void doBgPost(String key, final String iName) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_URL, key);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynModifyMeBg))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resAlertBg = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resAlertBg.getCode())) {
                            application.getCurUser().setUbackground(CommonConstants.YNQNURL + iName);
                            showToast("修改成功");
                            Intent mIntent = new Intent(ACTIONs.actionAlertMeBg);
                            sendBroadcast(mIntent);
                        } else {
                            showToast("修改失败");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
//                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 头像
            case R.id.rl_profile_avatar:
                isAvatar = true;
                mpopSetAvatar.showAtLocation(ProfileActivity.this.findViewById(R.id.main_content), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                ((TextView) mpopSetAvatar.mMenuView.findViewById(R.id.btn_alert_avatar_title)).setText("修改头像");
                break;
            // 背景
            case R.id.rl_profile_bg:
                isAvatar = false;
                mpopSetAvatar.showAtLocation(ProfileActivity.this.findViewById(R.id.main_content), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                ((TextView) mpopSetAvatar.mMenuView.findViewById(R.id.btn_alert_avatar_title)).setText("修改背景");
                break;
            // 昵称
            case R.id.rl_profile_name:
                Intent intent = new Intent(this, AlertNameActivity.class);
                intent.putExtra(CommonConstants.YNDATAS, curUser.getUnickname());
                startActivityForResult(intent, CommonConstants.REQ_ALERT_GNAME);
                break;
            // 性别
            case R.id.rl_profile_sex:
                String usex = tv_user_sex.getText().toString().trim();
                initAlertSex(usex);
                break;
            // 生日
            case R.id.rl_profile_birthday:
                String initStartDateTime = tv_user_birthday.getText().toString().trim();
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(ProfileActivity.this, initStartDateTime);
                dateTimePicKDialog.dateTimePicKDialog(tv_user_birthday);
                break;
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void updateTheme() {
        if (mToolbar != null) {
            try {
                Resources mResource = SkinPackageManager.getInstance(this).mResources;
                mToolbar.setNavigationIcon(mResource.getDrawable(mResource.getIdentifier("ic_return", "drawable", "com.github.postsanf.skinby")));
                mToolbar.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", "color", "com.github.postsanf.skinby")));
                mToolbar.setTitleTextColor(mResource.getColor(mResource.getIdentifier("border_color", "color", "com.github.postsanf.skinby")));
                mpopSetAvatar.btn_take_photo.setBackground(mResource.getDrawable(mResource.getIdentifier("btn_invite_bg_sel", "drawable", "com.github.postsanf.skinby")));
                mpopSetAvatar.btn_pick_photo.setBackground(mResource.getDrawable(mResource.getIdentifier("btn_invite_bg_sel", "drawable", "com.github.postsanf.skinby")));
                mpopSetAvatar.btn_cancel.setBackground(mResource.getDrawable(mResource.getIdentifier("btn_invite_bg_sel", "drawable", "com.github.postsanf.skinby")));
                mpopSetAvatar.btn_take_photo.setTextColor(mResource.getColorStateList(mResource.getIdentifier("btn_txtcolor_switch2theme", "drawable", "com.github.postsanf.skinby")));
                mpopSetAvatar.btn_pick_photo.setTextColor(mResource.getColorStateList(mResource.getIdentifier("btn_txtcolor_switch2theme", "drawable", "com.github.postsanf.skinby")));
                mpopSetAvatar.btn_cancel.setTextColor(mResource.getColorStateList(mResource.getIdentifier("btn_txtcolor_switch2theme", "drawable", "com.github.postsanf.skinby")));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApplication.getInstance().mActivitys.remove(this);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        if (SkinPackageManager.getInstance(this).mResources != null) {
            updateTheme();
        }
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
